package hutool.datasource.sqlserver;

import cn.hutool.db.ds.simple.SimpleDataSource;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeFilter;
import exam.io.IoUtils;
import org.apache.poi.ss.formula.functions.T;

import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/5/24 15:10
 * @since JDK 1.8
 */
public class SqlServer {

    public static void main(String[] args) throws Exception {

//       List<Map<String, Object>> mapList=selectMapList("SELECT TOP 1000 [Whir_U_Content_PID]\n" +
//               "      ,[Hits]\n" +
//               "      ,[Title]\n" +
//               "      ,[CategoryID]\n" +
//               "      ,[IsDefault]\n" +
//               "      ,[IsTop]\n" +
//               "      ,[ImageUrl]\n" +
//               "      ,[Content]\n" +
//               "      ,[MetaTitle]\n" +
//               "      ,[MetaKeyword]\n" +
//               "      ,[MetaDesc]\n" +
//               "      ,[RedirectUrl]\n" +
//               "      ,[EnableRedirectUrl]\n" +
//               "      ,[TypeID]\n" +
//               "      ,[SubjectID]\n" +
//               "      ,[State]\n" +
//               "      ,[Sort]\n" +
//               "      ,[IsDel]\n" +
//               "      ,[CreateDate]\n" +
//               "      ,[CreateUser]\n" +
//               "      ,[UpdateUser]\n" +
//               "      ,[UpdateDate]\n" +
//               "      ,[LinkUrl]\n" +
//               "      ,[Source]\n" +
//               "      ,[Work]\n" +
//               "      ,[Intro]\n" +
//               "      ,[VideoUrl]\n" +
//               "      ,[VideoFile]\n" +
//               "      ,[FileUpload]\n" +
//               "      ,[IsTopics]\n" +
//               "      ,[LinkName]\n" +
//               "      ,[Post]\n" +
//               "      ,[image]\n" +
//               "      ,[yes]\n" +
//               "      ,[Author]\n" +
//               "      ,[PDF]\n" +
//               "      ,[DateString]\n" +
//               "      ,[VisitsToday]\n" +
//               "  FROM [ZZB].[dbo].[Whir_U_Content]");
        List<Map<String, Object>> mapList=selectMapList("SELECT TOP 1000 [Whir_U_Content_PID]\n" +
                "      ,[Title]\n" +
                "      ,[ImageUrl]\n" +
                "      ,[Content]\n" +
                "      ,[MetaTitle]\n" +
                "      ,[MetaDesc]\n" +
                "      ,[Work]\n" +
                "  FROM [ZZB].[dbo].[Whir_U_Content]");
       mapList.forEach(e->{
           String content=e.get("Content")+"";
           content=matcherContents1(content);
           if(!"".equals(content)){
               System.out.println(content);
           }
       });

    }

    public static String matcherContents1(String content){
        Pattern p_src = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
        //让正则对象和要操作的字符串相关联；
        Matcher m = p_src.matcher(content);
        //m.find():将规则作用到字符串上，并进行符合规则的字串查找；
        StringBuilder stringBuilder=new StringBuilder();
        while (m.find()) {
            stringBuilder.append(m.group());
        }
        return stringBuilder.toString();
    }


    public static String matcherContents(String content){
        Pattern p_src = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
        //让正则对象和要操作的字符串相关联；
        Matcher m = p_src.matcher(content);
        //m.find():将规则作用到字符串上，并进行符合规则的字串查找；

        while (m.find()) {
            String grop=m.group();
            System.out.println(grop);
            String s=grop.replace("src=\"","src=/group/");
            s=s.replace("\"","'");
            content=content.replace(m.group(),s);
            // System.out.println(m.start() + "---" + m.end()); //获取找到字串的始末索引(包含头，不包含尾);
        }
        return content;
    }


    public static String arrMapToString(List<Map<String, Object>> mapList){
        return JSONObject.toJSONString(mapList, new SerializeFilter() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });
    }

    public static String arrayToString(List<T> tList){
        return JSONObject.toJSONString(tList);
    }

    public static  List<Map<String, Object>> stringToArray1(String str,Class<Map<String, Object>> cls){
        return JSONObject.parseArray(str,cls);
    }

    public static  <T> List<T> stringToArray(String str,Class<T> cls){
        return JSONObject.parseArray(str,cls);
    }



    /**
     * 查询集合
     *
     * 根据sql查询集合
     * @param sql
     * @return
     */
    public static List<Map<String, Object>> selectMapList(String sql){
        List<Map<String, Object>> mapList=null;
        ResultSet resultSet=sqlExecuteQuery(sql);
        if(resultSet==null){
            return mapList;
        }
        String[] fields=getFeildList(resultSet);
        try {
            mapList=new ArrayList<>(50);
            while (resultSet.next()){
                Map<String, Object> stringObjectMap=new HashMap<>();
                for (int i = 0; i < fields.length; i++) {
                    String feildName=fields[i];
                    Object value=resultSet.getObject(feildName);
                    stringObjectMap.put(feildName,value);
                }
                mapList.add(stringObjectMap);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return mapList;
    }


    //执行查询sql
    private static ResultSet sqlExecuteQuery(String sql){
        Statement stmt = null;
        Connection conn = null;
        ResultSet rs=null;
        try {
            conn=getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
        }catch (Exception e){
            e.printStackTrace();
        }
        return rs;
    }



    //获取字段列表
    private static String[] getFeildList(ResultSet rs){
        try {
            ResultSetMetaData rsmd = rs.getMetaData();
            String [] lie=new String[rsmd.getColumnCount()];
            for (int i = 1; i <rsmd.getColumnCount()+1; i++) {
                lie[i-1]=rsmd.getColumnName(i);
            }
            return lie;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new String[]{};
    }


    private static Connection getConnection() {
      //  DataSource ds = new SimpleDataSource("jdbc:sqlserver://192.168.217.134:1433;DatabaseName=Student", "SA","MyPassWord123","com.microsoft.sqlserver.jdbc.SQLServerDriver");
        DataSource ds = new SimpleDataSource("jdbc:sqlserver://localhost:49708;DatabaseName=ZZB", "SA","123456","com.microsoft.sqlserver.jdbc.SQLServerDriver");
        try {
            return ds.getConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
